<?php
/**
 * Created by PhpStorm.
 * User: lixy
 * Date: 2016/9/9
 * Time: 16:20
 */

namespace app\controllers;

use app\librarys\Tools;
use app\models\Mall;
use app\models\Pay;
use yii\helpers\Url;
use yii\web\Controller;
use Yii;

class PayIntegralController extends Controller
{
    public $layout = false;
    public $enableCsrfValidation = false;

    public function actionIndex($integral = 0, $order_code = '', $openid = '')
    {

        if (Pay::getOrder($order_code) == false) {
            var_dump($order_code);
            echo '订单不存在';
            exit;
        }

        $integral = intval($integral);
        if ($integral <= 0) {
            echo '购买积分不能小于0';
            exit;
        }
        //微信开启支付流程
        $weixinpayJs = "0";
        $out_trade_no = "";
        if ($openid) {
            $re = $this->cashWeixinPay($order_code, $openid, $integral);
            $weixinpayJs = $re['js'];
            $out_trade_no = $re['out_trade_no'];
        }
        return $this->render('index', [
            'integral' => $integral,
            'order_code' => $order_code,
            'openid' => $openid,
            'weixinpayJs' => $weixinpayJs,
            'out_trade_no' => $out_trade_no,
        ]);
    }

    public function renderJson($data = null, $status = 0, $message = 'success')
    {
        $result = [
            'status' => $status,
            'message' => $message,
            'data' => $data
        ];

        return json_encode($result, true);
    }

    //mall-m-weixin-pay-handle  ---微信客户端用
    public function actionMallMWeixinPayHandle()
    {
        $integral = Yii::$app->request->post('integral', 0);
        $orderCode = Yii::$app->request->post('orderCode', '');
        $trade_type = Yii::$app->request->post('trade_type', 'JSAPI');
        $openid = Mall::getWeixinOpenid();

        if ($openid) {
            $re = $this->cashWeixinPay($orderCode, $openid, $integral,$trade_type);
            if ($re) {
                $weixinpayJs = $re['js'];
                $out_trade_no = $re['out_trade_no'];
                return $this->renderJson([
                    'weixinpayJs' => json_decode($weixinpayJs),
                    'out_trade_no' => $out_trade_no,
                    'code_url'=>$re['code_url']
                ]);//
            } else {
                return $this->renderJson([], 1, '不能开启微信支付!');
            }
        } else {
            return $this->renderJson([], 1, '微信没有授权,不能开启支付!');
        }
    }
    //pc-weixin-pay-handle  ---pc版用
    public function actionPcWeixinPayHandle()
    {
        $integral = Yii::$app->request->post('integral', 0);
        $orderCode = Yii::$app->request->post('orderCode', '');
        $trade_type = 'NATIVE';

        $re = $this->cashWeixinPay($orderCode, '', $integral,$trade_type);
        if ($re) {
            $weixinpayJs = $re['js'];
            $out_trade_no = $re['out_trade_no'];
            return $this->renderJson([
                'weixinpayJs' => json_decode($weixinpayJs),
                'out_trade_no' => $out_trade_no,
                'code_url'=>$re['code_url']
            ]);//
        } else {
            return $this->renderJson([], 1, '不能开启微信支付!');
        }
    }
    //mall-alipay-pay
    public function actionMallAlipayPay()
    {
        $integral = Yii::$app->request->post("integral");
        $order_code = Yii::$app->request->post("order_code");
        $is_pc = Yii::$app->request->post("is_pc");
        $integral = intval($integral);
        if ($integral <= 0) {
            echo '购买积分不能小于0';
            exit;
        }

        //订单名称，必填
        $subject =  Pay::getOrderSubject($order_code);;
//        $subject = "购买{$integral}积分";
        //付款金额，必填(单位元)
        $total_fee = Pay::calcCash($integral);
        //调试用
        if(Mall::getCurrentInstitutionCode()=='JG000001') {
            $total_fee = 0.01;
        }
        //商户订单号，商户网站订单系统中唯一订单号，必填
        $payIntegralRecord =  Pay::addPayIntegralRecord('ali', $order_code, $integral);
        //数据库添加支付订单记录

        //收银台页面上，商品展示的超链接，必填
        if($is_pc){//pc
            $show_url = Url::to(['mall/order-list','institution_code'=>Mall::getCurrentInstitutionCode()],true);
            $return_url = Url::to(['pay-integral/cash-to-integral-alipay-pc-return'], true);
        }else{//wap
            $show_url = Url::to(['mall-m/order-list','institution_code'=>Mall::getCurrentInstitutionCode()],true);
            $return_url = Url::to(['pay-integral/cash-to-integral-alipay-return'], true);
        }
        //商品描述，可空
//        $body = "购买{$integral}积分";
        $body = $subject;
        $notify_url = Url::to(['pay-integral/cash-to-integral-alipay-notify'], true);
        /************************************************************/
        $this->cashAlipayApi($total_fee, $payIntegralRecord['out_trade_no'], $notify_url, $return_url, $subject, $body, $show_url,$is_pc);
    }

    //cash-to-integral-alipay-notify
    public function actionCashToIntegralAlipayNotify()
    {
        $result = $this->alipayNotifyAnalyze();
//        file_put_contents('../web/1.html',Tools::var_dump_out($result));
        if ($result) {
            //完成支付结果
            $re = Pay::endPayIntegralRecord($result['out_trade_no'], $result['trade_no']);
            if ($re) {
                echo 'success';
                exit;
            }

        }
        echo "fail";
    }
    //cash-to-integral-alipay-return
    public function actionCashToIntegralAlipayReturn()
    {
        $result = $this->alipayReturnAnalyze();
        if ($result) {
            //跳转
            return $this->redirect(['mall-m/pay-order-success','isMix'=>1,'out_trade_no'=>$result['out_trade_no'],'institution_code'=>Mall::getCurrentInstitutionCode()]);
        }else{
            echo 'pay return error';
            exit;
        }
    }
    //cash-to-integral-alipay-pc-return
    public function actionCashToIntegralAlipayPcReturn()
    {
        $result = $this->alipayReturnAnalyze();
        if ($result) {
            //跳转
            return $this->redirect(['mall/pay-order-success','out_trade_no'=>$result['out_trade_no'],'institution_code'=>Mall::getCurrentInstitutionCode()]);
        }else{
            echo 'pay return error';
            exit;
        }
    }
    private function cashAlipayApi($total_fee, $out_trade_no, $notify_url, $return_url, $subject, $body, $show_url,$is_pc)
    {
        ini_set('display_errors', 1);
        $alipay_config = [];
        require_once("../librarys/alipay/alipay.config.php");
        require_once("../librarys/alipay/lib/alipay_submit.class.php");
        if($is_pc){
            $alipay_config['service']=$alipay_config['create_direct_service'];
        }
        $parameter = array(
            "service" => $alipay_config['service'],
            "partner" => $alipay_config['partner'],
            "seller_id" => $alipay_config['seller_id'],
            "payment_type" => $alipay_config['payment_type'],
            "notify_url" => $notify_url,
            "return_url" => $return_url,
            "_input_charset" => trim(strtolower($alipay_config['input_charset'])),
            "out_trade_no" => $out_trade_no,
            "subject" => $subject,
            "total_fee" => $total_fee,
            "show_url" => $show_url,
            "body" => $body,

        );


//建立请求
        $alipaySubmit = new \AlipaySubmit($alipay_config);
        $html_text = $alipaySubmit->buildRequestForm($parameter, "get", "确认");
        echo $html_text;
        exit;

    }

    private function alipayReturnAnalyze()
    {
        ini_set('display_errors', 1);
        $alipay_config = [];
        require_once("../librarys/alipay/alipay.config.php");
        require_once("../librarys/alipay/lib/alipay_notify.class.php");
        //计算得出通知验证结果
        $alipayNotify = new \AlipayNotify($alipay_config);
        $verify_result = $alipayNotify->verifyReturn();
        if ($verify_result) {//验证成功
            //商户订单号
            $out_trade_no = $_GET['out_trade_no'];
            //支付宝交易号
            $trade_no = $_GET['trade_no'];
            //交易状态
            $trade_status = $_GET['trade_status'];
            if ($trade_status == 'TRADE_FINISHED' || $trade_status == 'TRADE_SUCCESS') {
                return [
                    'out_trade_no' => $out_trade_no,
                    'trade_no' => $trade_no,
                    'trade_status' => $trade_status,
                ];
            }


        }
        return false;
    }
    private function alipayNotifyAnalyze()
    {
        ini_set('display_errors', 1);
        $alipay_config = [];
        require_once("../librarys/alipay/alipay.config.php");
        require_once("../librarys/alipay/lib/alipay_notify.class.php");
        //计算得出通知验证结果
        $alipayNotify = new \AlipayNotify($alipay_config);
        $verify_result = $alipayNotify->verifyNotify();
        if ($verify_result) {//验证成功
            //商户订单号
            $out_trade_no = $_POST['out_trade_no'];
            //支付宝交易号
            $trade_no = $_POST['trade_no'];
            //交易状态
            $trade_status = $_POST['trade_status'];
            if ($trade_status == 'TRADE_FINISHED' || $trade_status == 'TRADE_SUCCESS') {
                return [
                    'out_trade_no' => $out_trade_no,
                    'trade_no' => $trade_no,
                    'trade_status' => $trade_status,
                ];
            }


        }
        return false;
    }
    //weixinpay
    private function cashWeixinPay($order_code, $openid, $integral,$trade_type='JSAPI')
    {
        ini_set('display_errors', 1);
        require_once("../librarys/weixinpay/lib/WxPay.Data.php");
        require_once("../librarys/weixinpay/lib/WxPay.JsApiPay.php");
        //付款金额，必填(单位  分)
        $total_fee = Pay::calcCash($integral) * 100;
        //调试用
        if(Mall::getCurrentInstitutionCode()=='JG000001'){
            $total_fee = 1;
        }
        //生成支付订单数据

        $payIntegralRecord = Pay::addPayIntegralRecord('wx', $order_code, $integral);
        //回调地址
        $notify_url = Url::to(['pay-integral/cash-to-integral-weixin-notify'], true);
        $subject = Pay::getOrderSubject($order_code);
//        $subject = "购买{$integral}积分";

        $input = new \WxPayUnifiedOrder();

        $input->SetBody($subject);
        $input->SetOut_trade_no($payIntegralRecord['out_trade_no']);
        $input->SetTotal_fee($total_fee);//单位分
        $input->SetTime_start(date("YmdHis"));
        //[time_expire时间过短，刷卡至少1分钟，其他5分钟]]  暂不设置这个参数
//        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetNotify_url($notify_url);
        $input->SetTrade_type($trade_type);
        $input->SetOpenid($openid);
        $input->SetAttach("");
        $input->SetProduct_id($order_code);
        $order = \WxPayApi::unifiedOrder($input);
//        var_dump($order);exit;
        //return_code 和result_code
//        return ['js'=> json_encode($order,JSON_UNESCAPED_UNICODE)];
        if ($order['return_code'] == 'SUCCESS' && $order['result_code'] == 'SUCCESS') {
            return ['js' => (new \JsApiPay())->GetJsApiParameters($order),
                'code_url'=>array_key_exists('code_url',$order) ? $order['code_url'] : '',//2个小时有效
                'out_trade_no' => $payIntegralRecord['out_trade_no'], 'id' => $payIntegralRecord['id'],];
        } else {
            return false;
        }
    }

    //cash-to-integral-weixin-notify
    public function actionCashToIntegralWeixinNotify()
    {
        try {
            $echostr = $this->_toXml("0");
            $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
            $data = json_decode(json_encode(simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA)), true);

            //写入数据库
            if ($data['return_code'] == 'SUCCESS') {
                $out_trade_no = $data['out_trade_no'];
                $trade_no = $data['transaction_id'];
                $re = Pay::endPayIntegralRecord($out_trade_no, $trade_no);
                if ($re) {
                    $echostr = $this->_toXml("1");
                }
            }

            echo $echostr;
        } catch (\Exception $e) {

        }

    }

    private function _toXml($isok)
    {
        $re = 'FAIL';
        if ($isok == '1') {
            $re = 'SUCCESS';
        }
        $res = "<xml>
              <return_code><![CDATA[$re]]></return_code>
              <return_msg><![CDATA[]]></return_msg>
            </xml>";
        return $res;
    }
}